package com.twang.stock.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.Entity.ShiShiData;
import com.twang.stock.common.http.HtmlTools;
import com.twang.stock.dto.TenXunStock;
import com.twang.stock.entity.CompanyStock;
import com.twang.stock.entity.CompanyStockMinutes;
import com.twang.stock.entity.DfcfBanKuaiMaoLiLv;
import com.twang.stock.entity.User;
import com.twang.stock.mapper.CompanyStockMapper;
import com.twang.stock.mapper.CompanyStockMinutesMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.CompanyStockService;
import com.twang.stock.service.IndexService;
import com.twang.stock.service.UserService;
import com.twang.stock.service.ZhangTingBanService;
import com.twang.stock.service.ZhangTingBanTaskService;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CompanyStockServiceImpl  implements CompanyStockService {
    @Resource
    private CompanyStockMapper companyStockMapper;

    @Autowired
    private UserService userService;

    @Resource
    private ZhangTingBanService zhangTingBanService;

    @Resource
    private CompanyStockMinutesMapper companyStockMinutesMapper;

    @Autowired
    private IndexService indexService;

    @Autowired
    private ZhangTingBanTaskService zhangTingBanTaskService;
    @Autowired
    private RedisUtil redisUtil;

    public static String ZI_XUAN_CHI_KEY="ZI_XUAN_CHI_KEY";

    @Override
    public List<CompanyStock> list() throws Exception {
        User user=userService.getUserByToken();
        Example example = new Example(CompanyStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",CompanyStockCommon.STATUS_生效);
        if(null!=user){
            criteria.andEqualTo("userId",user.getId());
        }else{
            throw new Exception("请登录！");
        }
        example.orderBy("zhiDing").desc();
        return companyStockMapper.selectByExample(example);
    }

    @Override
    public List<CompanyStock> selectById(Long userId) throws Exception {
        Example example = new Example(CompanyStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",CompanyStockCommon.STATUS_生效);
        if(null!=userId){
            criteria.andEqualTo("userId",userId);
        }else{
            throw new Exception("请输入ID");
        }
        example.orderBy("zhiDing").desc();
        return companyStockMapper.selectByExample(example);
    }

    @Override
    public void addStock(String code, String desc,Long uesrId,TenXunStock tenXunStock) throws Exception {
        //获取表单控件值
        ShiShiData shiShiData = new ShiShiData();
        try {
            shiShiData = HtmlTools.getGpdatas(Lists.newArrayList(code)).get(0);
        } catch (Exception e) {
                shiShiData.setGpname(tenXunStock.getStockName());
                shiShiData.setSumvol(tenXunStock.getTradingVolume().intValue());
        }

        CompanyStock companyStock = new CompanyStock();
        companyStock.setCompanyCode(code);
        companyStock.setCompanyName(shiShiData.getGpname());
        companyStock.setTradingVolume(new BigDecimal(shiShiData.getSumvol()).setScale(2, BigDecimal.ROUND_HALF_UP));
        companyStock.setTradingAmount(new BigDecimal(shiShiData.getSumvol()).setScale(2, BigDecimal.ROUND_HALF_UP));
        //
        String ztDesc = zhangTingBanService.zhangtingReason(code);
        if (StringUtils.isNotBlank(ztDesc)) {
            desc = ztDesc;
        }
        companyStock.setStockDesc(desc);
        User user = userService.getUserByToken();
        if (null == user) {
            companyStock.setUserId(uesrId.intValue());
        } else {
            companyStock.setUserId(user.getId().intValue());
        }
        companyStock.setUpdateTime(new Date());
        companyStock.setCreateTime(new Date());
        //
        CompanyStock param = new CompanyStock();
        param.setCompanyCode(code);
        param.setUserId(companyStock.getUserId());
        List<CompanyStock> result = companyStockMapper.select(param);
        if (result.size() < 1) {
            companyStock.setDate(HolidayCopy.getRealToday());
            companyStock.setStatus(CompanyStockCommon.STATUS_生效);
            companyStock.setWarn(CompanyStockCommon.WARN_未触发预警);
            companyStock.setZhiDing(CompanyStockCommon.非置顶);
            companyStockMapper.insert(companyStock);
        } else {
            companyStock.setId(result.get(0).getId());
            companyStock.setStatus(CompanyStockCommon.STATUS_生效);
            companyStock.setWarn(CompanyStockCommon.WARN_未触发预警);
            companyStock.setZhiDing(CompanyStockCommon.非置顶);
            companyStock.setStockDesc(desc);
            companyStock.setDate(HolidayCopy.getRealToday());
            companyStockMapper.updateByPrimaryKey(companyStock);
        }
    }

    @Override
    public void delStock(Integer id) {
        CompanyStock companyStock = new CompanyStock();
        companyStock.setId(id);
        CompanyStock result=  companyStockMapper.selectByPrimaryKey(companyStock);
        companyStockMapper.deleteByPrimaryKey(result);
    }

    @Override
    public void zhiDingStock(Integer id) {
        CompanyStock companyStock = new CompanyStock();
        companyStock.setId(id);
        CompanyStock temp = companyStockMapper.selectOne(companyStock);
        if (temp != null) {
            temp.setZhiDing(CompanyStockCommon.置顶);
            companyStockMapper.updateByPrimaryKey(temp);
        }
    }

    @Override
    public List<DfcfBanKuaiMaoLiLv> query() throws Exception {
        List<CompanyStock> companyStocksList = this.list();
        List<CompanyStockMinutes> companyStockMinutesList = Lists.newArrayList();
        List<DfcfBanKuaiMaoLiLv> maoLiLvs = Lists.newArrayList();
        User user = userService.getUserByToken();
        StringBuffer keybf = new StringBuffer(ZI_XUAN_CHI_KEY);
        if (null == user) {
            return null;
        }
        keybf.append("_").append(user.getId());
        Object obj = redisUtil.get(keybf.toString());
        if (null == obj) {
            if (CollectionUtils.isNotEmpty(companyStocksList)) {
                companyStocksList.stream().forEach(item -> {
                    companyStockMinutesList.add(companyStockMinutesMapper.queryByCode(item.getCompanyCode()));
                });
                indexService.getDfcfBanKuaiMaoLiLvs(maoLiLvs, companyStockMinutesList);
                //看点
                zhangTingBanTaskService.initKanDian(maoLiLvs, Boolean.TRUE);

                //30 Min 成交额
                zhangTingBanTaskService.getTrade30MinutesVol(maoLiLvs);
                redisUtil.set(keybf.toString(),JSONObject.toJSONString(maoLiLvs));
            }
        } else {
            maoLiLvs = JSONObject.parseArray(obj.toString(), DfcfBanKuaiMaoLiLv.class);
        }

        return maoLiLvs;
    }

    public static class  CompanyStockCommon {
        //
        public static Integer 置顶 = 1;
        //
        public static Integer 非置顶 = 1;
        //
        public static Integer STATUS_生效 = 0;
        //
        public static Integer STATUS_失效 = 1;
        //
        public static Integer WARN_触发预警 = 1;

        public static Integer WARN_未触发预警 = 1;
    }
}
